package com.keyou.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.keyou.reggie.common.CommonConstants;
import com.keyou.reggie.common.ResultInfo;
import com.keyou.reggie.entity.User;
import com.keyou.reggie.service.UserService;
import com.keyou.reggie.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: klq
 * @Date: 2023/1/12 14:17
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/test")
    public ResultInfo<List<User>> testXmlSql(@RequestParam String mail) {
        log.info("测试通过xml的sql语句获取数据库数据。。。");
        return ResultInfo.success(userService.getUsersByMail(mail));
    }

    /**
     * 发送验证码
     *
     * @param session
     * @param user
     * @return
     */
    @PostMapping("/senMsg")
    public ResultInfo<String> sendMsg(HttpSession session, @RequestBody User user) {
        //前端目前实现的是传phone验证，后端资源有限实现的是邮箱验证，故mail取user.phone
        String mail = user.getPhone();
        if (StringUtils.isNotEmpty(mail)) {
            try {
                //随机生成一个验证码
                String achieveCode = MailUtil.achieveCode();
                //往邮箱发送验证码
                MailUtil.sendTestMail(mail, achieveCode);

                //验证码存session，方便后面拿出来比对
                //session.setAttribute(mail, achieveCode);
                //验证码缓存到Redis，设置存活时间5分钟
                redisTemplate.opsForValue().set(mail, achieveCode, 5, TimeUnit.MINUTES);
                log.info("本次登录的用户为：{}，生成的验证码为：{}", mail, achieveCode);
                return ResultInfo.success(null, "验证码发送成功");
            } catch (MessagingException e) {
                e.printStackTrace();
                return ResultInfo.success(null, "验证码发送失败");
            }
        }
        return ResultInfo.success(null, "验证码发送失败");
    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public ResultInfo<User> login(@RequestBody Map<String, Object> map, HttpSession session) {
        //获取手机号（QQ邮箱）
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();

        //从session中获取验证码
        //String codeInSession = session.getAttribute(phone).toString();
        String codeInRedis = redisTemplate.opsForValue().get(phone);
        log.info("你输入的：code{}，redis中的code：{}，计算结果为：{}", code, codeInRedis, (code != null && code.equals(codeInRedis)));

        //比较这用户输入的验证码和session中存的验证码是否一致
        if (code != null && code.equals(codeInRedis)) {
            //如果输入正确，判断一下当前用户是否存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            //判断依据是从数据库中查询是否有其手机号（QQ邮箱）
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            //如果不存在，则创建一个，存入数据库
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
                user.setName("用户" + codeInRedis);
            }
            //存个session，表示登录状态
            session.setAttribute(CommonConstants.SESSION_USER, user.getId());
            //如果登录成功，则删除Redis中的验证码
            redisTemplate.delete(phone);
            return ResultInfo.success(user);
        }

        return ResultInfo.error("登录失败");
    }

    @PostMapping("/loginout")
    public ResultInfo<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return ResultInfo.success("退出成功");
    }

}